package com.lyeducation.services.category;

import com.lyeducation.entities.course.CategoryEntity;
import com.lyeducation.entities.course.CourseEntity;
import com.lyeducation.entities.course.middle.CategoryCourseEntity;
import com.lyeducation.repository.CategoryRepository;
import com.lyeducation.services.base.BaseServiceImpl;
import com.lyeducation.util.KeyUtil;
import com.lyeducation.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CategoryServiceImpl
 * @Description
 * @Author Sky1in3
 * @Date 2019/1/26 14:12
 * @Version 1.0
 */
@Service
public class CategoryServiceImpl extends BaseServiceImpl<CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public boolean addCategory(CategoryEntity categoryEntity) {
        String chapterId = KeyUtil.genUniqueKey();
        categoryEntity.setId(chapterId);
        if (categoryRepository.save(categoryEntity) != null) {
            return true;
        }
        return false;
    }

    @Override
    public CategoryEntity updateCategory(CategoryEntity categoryEntity) {
        if (StringUtils.isNotBlank(categoryEntity.getId())) {
            CategoryEntity category = categoryRepository.findById(categoryEntity.getId());
            if (category != null) {
                return categoryRepository.update(categoryEntity);
            }
        }
        return null;
    }

    @Override
    public boolean deleteCategory(String categoryId) {
        if (StringUtils.isNotBlank(categoryId)) {
            if (categoryRepository.deleteById(categoryId)) {
                return categoryRepository.delMiddleTable(CategoryCourseEntity.class, "categoryId", categoryId, null, null);
            }
        }
        return false;
    }

    @Override
    public CategoryEntity findOne(String categoryId) {
        if (StringUtils.isNotBlank(categoryId)) {
            CategoryEntity categoryEntity = categoryRepository.findById(categoryId);

            List<CategoryCourseEntity> categoryCourseEntityList = categoryRepository.findByFiled(CategoryCourseEntity.class, "categoryId", categoryId);
            List list = new ArrayList();
            for (int i = 0; i < categoryCourseEntityList.size(); i++) {
                CourseEntity courseEntity = categoryRepository.findById(CourseEntity.class, categoryCourseEntityList.get(i).getCourseId());
                list.add(courseEntity);
            }
            categoryEntity.setCourseEntityList(list);
            return categoryEntity;
        }
        return null;
    }

    @Override
    public Map<String, Object> categoryEntityList(int pageNo, int pageSize) {
        return categoryRepository.findPageByNativeQueryFileds("select * from category", null, pageNo, pageSize);
    }
}
